﻿using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;

namespace WebDAV;

public class ScreenShareHub : Hub
{
    // 存储所有连接的客户端
    private static readonly ConcurrentDictionary<string, string> _connections = new();

    // 当前屏幕共享者的连接ID
    private static string _currentScreenSharerId = string.Empty;

    // 客户端加入房间
    public override async Task OnConnectedAsync()
    {
        var connectionId = Context.ConnectionId;
        _connections.TryAdd(connectionId, Context.User?.Identity?.Name ?? "Anonymous");
        
        // 通知新用户当前屏幕共享状态
        if (!string.IsNullOrEmpty(_currentScreenSharerId))
        {
            await Clients.Client(connectionId).SendAsync("ScreenShareStarted", _currentScreenSharerId);
        }
        
        await base.OnConnectedAsync();
    }

    // 客户端断开连接
    public override async Task OnDisconnectedAsync(Exception exception)
    {
        _connections.TryRemove(Context.ConnectionId, out _);
        
        // 如果断开的是当前屏幕共享者
        if (Context.ConnectionId == _currentScreenSharerId)
        {
            _currentScreenSharerId = string.Empty;
            await Clients.All.SendAsync("ScreenShareStopped");
        }
        
        await base.OnDisconnectedAsync(exception);
    }

    // 发送信令数据
    public async Task SendSignal(string targetConnectionId, object signalData)
    {
        await Clients.Client(targetConnectionId).SendAsync("ReceiveSignal", Context.ConnectionId, signalData);
    }

    // 广播信令数据（用于新用户加入时的初始协商）
    public async Task BroadcastSignal(object signalData)
    {
        await Clients.Others.SendAsync("ReceiveSignal", Context.ConnectionId, signalData);
    }

    // 开始屏幕共享（由共享者调用）
    public async Task StartScreenShare()
    {
        _currentScreenSharerId = Context.ConnectionId;
        await Clients.All.SendAsync("ScreenShareStarted", Context.ConnectionId);
    }

    // 停止屏幕共享（由共享者调用）
    public async Task StopScreenShare()
    {
        if (_currentScreenSharerId == Context.ConnectionId)
        {
            _currentScreenSharerId = string.Empty;
            await Clients.All.SendAsync("ScreenShareStopped");
        }
    }

    // 获取所有连接的用户（用于显示用户列表）
    public async Task<Dictionary<string, string>> GetConnectedUsers()
    {
        return _connections.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
    }
}